package com.alex.server.config.filter;

import com.alex.server.pojo.Menu;
import com.alex.server.pojo.Role;
import com.alex.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

/**
 * 权限控制
 * 跟据请求url分析请求所需的角色
 */
@Component
public class CustomerFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private IMenuService menuService;
    AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menusWithRole = menuService.getMenusWithRole();

        for (Menu menu :menusWithRole){
            //判断请求url与菜单角色是否匹配,如果匹配代表
            if (antPathMatcher.match(menu.getUrl(),requestUrl)){
                //拿到能访问该菜单的角色,放进Collection集合中,然后把他与CustomUrlDecisionManager中的登录用户所拥有的角色进行比较
                String[] strings = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                List<ConfigAttribute> list = SecurityConfig.createList(strings);
                return list;
            }
        }
        //没匹配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
